import BScroll from '@better-scroll/core'
import ObserveDOM from '@better-scroll/observe-dom'
import { onActivated, onDeactivated, onMounted, onUnmounted, ref } from 'vue'

BScroll.use(ObserveDOM)

export default function useScroll(wrapperRef, options) {
  const scroll = ref(null)
  let scrollVal = scroll.value

  onMounted(() => {
    scrollVal = new BScroll(wrapperRef.value, {
      observeDOM: true,
      ...options.value
    })
  })

  onUnmounted(() => scrollVal.destroy())

  onActivated(() => {
    scrollVal.enable()
    scrollVal.refresh()
  })

  onDeactivated(() => scrollVal.disable())

  return scroll
}
